<?php


class DB_URL extends ORM_Table {

    static protected $table_name = 'url';

    static public function getTableName($params = null) {
        //$table_name = self::$table_name.substr($params['article_type_id'], 0, 1);
        return self::$table_name;
    }

    public function save(){
        $uhash  = $this->getUhash();
        $url    = $this->getUrl();
        parent::save();
        //创建文件缓存
        createHashUrlDir($uhash, $this->getArray());
        //创建memcache缓存
//        $memcache   = MemcacheAction::getCache();
//        $memcache->set('url_'.$uhash, $this->getArray());
        
        
    }
    
    static public function add($url_info, $cate_id=-999,$uid=0,$sina_url=null) {
        //$web    = getWebInfo($url);
        $uhash  = self::getHash($url_info);
        //$title  = getUrlTitle($url_info);
        $title  = 'no';
        $url    = new DB_URL();
        $url->setCateId(-999);
        $url->setUhash($uhash);
        $url->setUrl($url_info);
        $url->setTitle($title);
        $url->setUid($uid);
        $url->setCreated(time());
        $url->setIp($_SERVER['REMOTE_ADDR']);
        if($sina_url) {
            $url->setSinaUrl($sina_url);
        }
        //$url->setTencentUrl($_SESSION['tencent_url']);
        
        $url->save();


        unset($_SESSION['sina_url']);
        unset($_SESSION['tencent_url']);
        return $url;
    }
    
    //检测是否存在
    static function checkUhash($uhash){
        $num = ORM_Finder::findCount(DB_URL, "uhash='$uhash'");
        return $num;
    }

    //获取唯一HASH字符串
    static function getHash($url) {
        
        $arr    = short_url($url);
        $total  = count($arr);
        $hash   = null;
        
        //生成唯一的key
        foreach ($arr as $key => $va) {
            //查找key
            $has    = self::checkUhash($va);
            if(!$has){
                $hash   = $va;
                break;
            }
        }
        
        if($has == null || empty($hash)){
            $hash   = short_url(time().mt_rand(10000, 99999999));
            return $hash['0'];
        }
        
        return $hash;
    }

    //更新点击数据
    static function updateClick($uhash) {
        
    }
    //更新统计信息
    static function updateCount($uhash) {
        
    }
}

